<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>会议纪要工具</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      
      body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        padding: 20px;
      }
      
      .container {
        max-width: 1200px;
        margin: 0 auto;
        background: white;
        border-radius: 20px;
        box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        overflow: hidden;
      }
      
      .header {
        background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
        color: white;
        padding: 25px;
        text-align: center;
      }
      
      .header h1 {
        font-size: 2.2em;
        margin-bottom: 8px;
        font-weight: 300;
      }
      
      .header p {
        font-size: 1em;
        opacity: 0.9;
      }
      
      .controls {
        padding: 30px;
        background: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 20px;
        flex-wrap: wrap;
      }
      
      .language-selector {
        display: flex;
        align-items: center;
        gap: 15px;
        background: white;
        padding: 15px 25px;
        border-radius: 50px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
      }
      
      .language-selector select {
        padding: 10px 15px;
        border: 2px solid #e9ecef;
        border-radius: 25px;
        font-size: 16px;
        background: white;
        cursor: pointer;
        transition: all 0.3s ease;
      }
      
      .language-selector select:focus {
        outline: none;
        border-color: #4facfe;
        box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
      }
      
      .swap-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        padding: 12px;
        border-radius: 50%;
        cursor: pointer;
        font-size: 18px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
      }
      
      .swap-btn:hover {
        transform: rotate(180deg);
        box-shadow: 0 6px 20px rgba(0,0,0,0.3);
      }
      
      .meeting-area {
        display: flex;
        height: 700px;
      }
      
      .sidebar {
        width: 350px;
        background: #f8f9fa;
        border-right: 1px solid #e9ecef;
        padding: 25px;
        overflow-y: auto;
      }
      
      .main-content {
        flex: 1;
        display: flex;
        flex-direction: column;
      }
      
      .translation-panel {
        padding: 30px;
        position: relative;
        display: flex;
        flex-direction: column;
      }
      
      .translation-panel:first-child {
        border-right: 1px solid #e9ecef;
      }
      
      .panel-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f8f9fa;
      }
      
      .panel-title {
        font-size: 1.3em;
        font-weight: 600;
        color: #495057;
        display: flex;
        align-items: center;
        gap: 10px;
      }
      
      .panel-actions {
        display: flex;
        gap: 10px;
      }
      
      .action-btn {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        padding: 8px 12px;
        border-radius: 8px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
      }
      
      .action-btn:hover {
        background: #e9ecef;
        border-color: #adb5bd;
      }
      
      .text-area {
        flex: 1;
        border: 2px solid #e9ecef;
        border-radius: 15px;
        padding: 20px;
        font-size: 16px;
        line-height: 1.6;
        resize: none;
        outline: none;
        transition: all 0.3s ease;
        font-family: inherit;
      }
      
      .text-area:focus {
        border-color: #4facfe;
        box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
      }
      
      .text-area::placeholder {
        color: #adb5bd;
      }
      
      .status-indicator {
        position: absolute;
        top: 20px;
        right: 20px;
        padding: 5px 10px;
        border-radius: 15px;
        font-size: 12px;
        font-weight: 500;
      }
      
      .status-translating {
        background: #fff3cd;
        color: #856404;
        border: 1px solid #ffeaa7;
      }
      
      .status-complete {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
      }
      
      .status-error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
      }
      
      .char-count {
        margin-top: 10px;
        font-size: 12px;
        color: #6c757d;
        text-align: right;
      }
      
      .loading {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #4facfe;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      
      .fade-in {
        animation: fadeIn 0.5s ease-in;
      }
      
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }
      
      @media (max-width: 768px) {
        .translation-area {
          grid-template-columns: 1fr;
        }
        
        .translation-panel:first-child {
          border-right: none;
          border-bottom: 1px solid #e9ecef;
        }
        
        .controls {
          flex-direction: column;
        }
        
        .language-selector {
          flex-direction: column;
          text-align: center;
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h1>🌐 实时翻译工具</h1>
        <p>智能AI翻译，支持多种语言实时互译</p>
      </div>
      
      <div class="controls">
        <div class="language-selector">
          <select id="source-lang">
            <option value="auto">🌍 自动检测</option>
            <option value="A">🇨🇳 中文</option>
            <option value="B">🇬🇧 English</option>
            <option value="D">🇧🇷 Português</option>
            <option value="C">🇸🇦 العربية</option>
            <option value="E">🇷🇺 Русский</option>
            <option value="F">🇮🇳 हिन्दी</option>
          </select>
          
          <button class="swap-btn" onclick="swapLanguages()" title="交换语言">⇄</button>
          
          <select id="target-lang">
            <option value="B">🇬🇧 English</option>
            <option value="A">🇨🇳 中文</option>
            <option value="D">🇧🇷 Português</option>
            <option value="C">🇸🇦 العربية</option>
            <option value="E">🇷🇺 Русский</option>
            <option value="F">🇮🇳 हिन्दी</option>
          </select>
        </div>
      </div>
      
      <div class="translation-area">
        <div class="translation-panel">
          <div class="panel-header">
            <div class="panel-title">
              <span id="source-lang-flag">🌍</span>
              <span id="source-lang-name">自动检测</span>
            </div>
            <div class="panel-actions">
              <button class="action-btn" onclick="clearSource()" title="清除文本">🗑️</button>
              <button class="action-btn" onclick="pasteText()" title="粘贴文本">📋</button>
            </div>
          </div>
          
          <textarea 
            id="source-text" 
            class="text-area" 
            placeholder="请输入要翻译的文本..."
            oninput="handleInputChange()"
          ></textarea>
          
          <div class="char-count">
            <span id="source-char-count">0</span> 字符
          </div>
        </div>
        
        <div class="translation-panel">
          <div class="panel-header">
            <div class="panel-title">
              <span id="target-lang-flag">🇬🇧</span>
              <span id="target-lang-name">English</span>
            </div>
            <div class="panel-actions">
              <button class="action-btn" onclick="copyTranslation()" title="复制翻译结果">📋</button>
              <button class="action-btn" onclick="speakTranslation()" title="朗读翻译结果">🔊</button>
            </div>
          </div>
          
          <textarea 
            id="target-text" 
            class="text-area" 
            placeholder="翻译结果将显示在这里..."
            readonly
          ></textarea>
          
          <div class="char-count">
            <span id="target-char-count">0</span> 字符
            <span id="translation-status" style="float: right;"></span>
          </div>
        </div>
      </div>
    </div>

    <script>
      /**
       * 实时翻译工具 - JavaScript版本
       * 支持多种语言的实时翻译功能
       */

      // API配置
      const API_CONFIG = {
        URL: 'http://8.134.137.7/v1/chat-messages',
        HHH: 'app-qjYwY5kkqkTIEDN7AHJ2sgLU'
      };

      // 语言映射配置
      const LANGUAGE_CONFIG = {
        'auto': { name: '自动检测', flag: '🌍' },
        'A': { name: '中文', flag: '🇨🇳' },
        'B': { name: 'English', flag: '🇬🇧' },
        'D': { name: 'Português', flag: '🇧🇷' },
        'C': { name: 'العربية', flag: '🇸🇦' },
        'E': { name: 'Русский', flag: '🇷🇺' },
        'F': { name: 'हिन्दी', flag: '🇮🇳' }
      };

      // 翻译状态管理
      let translationTimeout = null;
      let isTranslating = false;
      let translationHistory = [];

      /**
       * 获取语言名称和图标
       */
      function getLanguageInfo(langCode) {
        return LANGUAGE_CONFIG[langCode] || { name: '未知语言', flag: '❓' };
      }

      /**
       * 更新语言选择器显示
       */
      function updateLanguageDisplay() {
        const sourceLang = document.getElementById('source-lang').value;
        const targetLang = document.getElementById('target-lang').value;
        
        const sourceInfo = getLanguageInfo(sourceLang);
        const targetInfo = getLanguageInfo(targetLang);
        
        document.getElementById('source-lang-flag').textContent = sourceInfo.flag;
        document.getElementById('source-lang-name').textContent = sourceInfo.name;
        document.getElementById('target-lang-flag').textContent = targetInfo.flag;
        document.getElementById('target-lang-name').textContent = targetInfo.name;
      }

      /**
       * 交换源语言和目标语言
       */
      function swapLanguages() {
        const sourceLang = document.getElementById('source-lang');
        const targetLang = document.getElementById('target-lang');
        const sourceText = document.getElementById('source-text');
        const targetText = document.getElementById('target-text');
        
        // 交换语言选择
        const tempLang = sourceLang.value;
        sourceLang.value = targetLang.value;
        targetLang.value = tempLang;
        
        // 交换文本内容
        const tempText = sourceText.value;
        sourceText.value = targetText.value;
        targetText.value = tempText;
        
        // 更新显示
        updateLanguageDisplay();
        updateCharCount();
        
        // 如果源文本不为空，重新翻译
        if (sourceText.value.trim()) {
          debouncedTranslate();
        }
      }

      /**
       * 更新字符计数
       */
      function updateCharCount() {
        const sourceText = document.getElementById('source-text').value;
        const targetText = document.getElementById('target-text').value;
        
        document.getElementById('source-char-count').textContent = sourceText.length;
        document.getElementById('target-char-count').textContent = targetText.length;
      }

      /**
       * 更新翻译状态
       */
      function updateTranslationStatus(status, message = '') {
        const statusElement = document.getElementById('translation-status');
        
        switch (status) {
          case 'translating':
            statusElement.innerHTML = '<div class="loading"></div> 翻译中...';
            statusElement.className = 'status-indicator status-translating';
            break;
          case 'complete':
            statusElement.textContent = '✅ 翻译完成';
            statusElement.className = 'status-indicator status-complete';
            setTimeout(() => {
              statusElement.textContent = '';
              statusElement.className = '';
            }, 2000);
            break;
          case 'error':
            statusElement.textContent = `❌ ${message}`;
            statusElement.className = 'status-indicator status-error';
            break;
          default:
            statusElement.textContent = '';
            statusElement.className = '';
        }
      }

      /**
       * 向Dify API发送翻译请求
       */
      async function translateText(text, sourceLang, targetLang) {
        if (!text.trim()) {
          document.getElementById('target-text').value = '';
          return '';
        }

        const headers = {
          'Authorization': `Bearer ${API_CONFIG.HHH}`,
          'Content-Type': 'application/json'
        };

        const data = {
          inputs: {
            source_language: sourceLang,
            target_language: targetLang,
            original_text: text
          },
          query: `请将以下文本从${getLanguageInfo(sourceLang).name}翻译为${getLanguageInfo(targetLang).name}：${text}`,
          response_mode: 'streaming',
          user: 'realtime-translator'
        };

        try {
          const response = await fetch(API_CONFIG.URL, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(data)
          });

          if (!response.ok) {
            throw new Error(`HTTP错误! 状态: ${response.status}`);
          }

          return await parseStreamResponse(response);
        } catch (error) {
          console.error('翻译请求失败:', error);
          throw error;
        }
      }

      /**
       * 解析流式响应
       */
      async function parseStreamResponse(response) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let result = '';

        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value, { stream: true });
            const lines = chunk.split('\n');

            for (const line of lines) {
              if (line.startsWith('data: ')) {
                try {
                  const jsonData = line.substring(6);
                  const parsedData = JSON.parse(jsonData);
                  const answer = parsedData.answer || '';
                  
                  result += answer;
                  // 实时更新翻译结果
                  document.getElementById('target-text').value = result;
                  updateCharCount();
                } catch (parseError) {
                  console.warn('解析错误:', parseError);
                  continue;
                }
              }
            }
          }
        } finally {
          reader.releaseLock();
        }

        return result;
      }

      /**
       * 执行翻译（带防抖）
       */
      async function performTranslation() {
        if (isTranslating) return;

        const sourceText = document.getElementById('source-text').value;
        const sourceLang = document.getElementById('source-lang').value;
        const targetLang = document.getElementById('target-lang').value;

        if (!sourceText.trim() || !targetLang) {
          document.getElementById('target-text').value = '';
          updateCharCount();
          return;
        }

        isTranslating = true;
        updateTranslationStatus('translating');

        try {
          await translateText(sourceText, sourceLang, targetLang);
          updateTranslationStatus('complete');
          
          // 添加到历史记录
          addToHistory(sourceText, document.getElementById('target-text').value, sourceLang, targetLang);
        } catch (error) {
          updateTranslationStatus('error', error.message);
        } finally {
          isTranslating = false;
        }
      }

      /**
       * 防抖翻译
       */
      function debouncedTranslate() {
        if (translationTimeout) {
          clearTimeout(translationTimeout);
        }
        
        translationTimeout = setTimeout(() => {
          performTranslation();
        }, 500); // 500ms防抖延迟
      }

      /**
       * 处理输入变化
       */
      function handleInputChange() {
        updateCharCount();
        debouncedTranslate();
      }

      /**
       * 清除源文本
       */
      function clearSource() {
        document.getElementById('source-text').value = '';
        document.getElementById('target-text').value = '';
        updateCharCount();
        updateTranslationStatus('');
      }

      /**
       * 粘贴文本
       */
      async function pasteText() {
        try {
          const text = await navigator.clipboard.readText();
          document.getElementById('source-text').value = text;
          updateCharCount();
          handleInputChange();
        } catch (error) {
          alert('无法访问剪贴板，请手动粘贴');
        }
      }

      /**
       * 复制翻译结果
       */
      async function copyTranslation() {
        const targetText = document.getElementById('target-text').value;
        if (!targetText) {
          alert('没有可复制的翻译结果');
          return;
        }

        try {
          await navigator.clipboard.writeText(targetText);
          updateTranslationStatus('complete');
        } catch (error) {
          alert('复制失败，请手动复制');
        }
      }

      /**
       * 朗读翻译结果
       */
      function speakTranslation() {
        const targetText = document.getElementById('target-text').value;
        if (!targetText) {
          alert('没有可朗读的翻译结果');
          return;
        }

        if ('speechSynthesis' in window) {
          const utterance = new SpeechSynthesisUtterance(targetText);
          const targetLang = document.getElementById('target-lang').value;
          
          // 设置语言
          const langMap = {
            'A': 'zh-CN',
            'B': 'en-US',
            'D': 'pt-BR',
            'C': 'ar-SA',
            'E': 'ru-RU',
            'F': 'hi-IN'
          };
          
          if (langMap[targetLang]) {
            utterance.lang = langMap[targetLang];
          }
          
          speechSynthesis.speak(utterance);
        } else {
          alert('您的浏览器不支持语音朗读功能');
        }
      }

      /**
       * 添加到历史记录
       */
      function addToHistory(sourceText, targetText, sourceLang, targetLang) {
        const historyItem = {
          sourceText,
          targetText,
          sourceLang,
          targetLang,
          timestamp: new Date().toLocaleString()
        };
        
        translationHistory.unshift(historyItem);
        
        // 只保留最近20条记录
        if (translationHistory.length > 20) {
          translationHistory = translationHistory.slice(0, 20);
        }
        
        // 可以在这里添加历史记录的UI显示
        console.log('翻译历史:', translationHistory);
      }

      /**
       * 监听语言选择变化
       */
      function setupLanguageListeners() {
        document.getElementById('source-lang').addEventListener('change', () => {
          updateLanguageDisplay();
          if (document.getElementById('source-text').value.trim()) {
            debouncedTranslate();
          }
        });
        
        document.getElementById('target-lang').addEventListener('change', () => {
          updateLanguageDisplay();
          if (document.getElementById('source-text').value.trim()) {
            debouncedTranslate();
          }
        });
      }

      // 初始化
      document.addEventListener('DOMContentLoaded', function() {
        updateLanguageDisplay();
        updateCharCount();
        setupLanguageListeners();
        
        // 设置焦点到源文本输入框
        document.getElementById('source-text').focus();
      });

      // 键盘快捷键
      document.addEventListener('keydown', function(event) {
        // Ctrl+Enter 触发翻译
        if (event.ctrlKey && event.key === 'Enter') {
          event.preventDefault();
          performTranslation();
        }
        
        // Ctrl+L 交换语言
        if (event.ctrlKey && event.key === 'l') {
          event.preventDefault();
          swapLanguages();
        }
        
        // Ctrl+Shift+C 复制翻译结果
        if (event.ctrlKey && event.shiftKey && event.key === 'C') {
          event.preventDefault();
          copyTranslation();
        }
      });
    </script>
  </body>
</html>
